package com.wangbo.box.mediator;

import java.util.ArrayList;
import java.util.List;

/**
 * 中介者模式
 *
 * 定义一个中介对象来封装一系列对象之间的交互，使原有对象之间的耦合松散，且可以独立地改变它们之间的交互。中介者模式又叫调停模式，它是迪米特法则的典型应用。
 */
public class MediatorPattern {


    static abstract class Mediator{
        abstract void register(Subject subject);
        abstract void relay(Subject subject);
    }

    static class RealMediator extends Mediator{
        List<Subject> subjectList = new ArrayList<>();

        @Override
        void register(Subject subject) {
            if (!subjectList.contains(subject)) {
                subjectList.add(subject);
                subject.setMediator(this);
            }
        }

        @Override
        void relay(Subject subject) {
            subjectList.forEach(s-> {
                if (s != subject){
                    s.receive();
                }
            });
        }
    }

    static abstract class Subject{
        Mediator mediator;

        public void setMediator(Mediator mediator) {
            this.mediator = mediator;
        }

        abstract void receive();
        abstract void send();
    }

    static class SubjectA extends Subject{

        @Override
        void receive() {
            System.out.println("subject A receive");
        }

        @Override
        void send() {
            System.out.println("subject A send");
            super.mediator.relay(this);
        }
    }

    static class SubjectB extends Subject{

        @Override
        void receive() {
            System.out.println("subject B receive");
        }

        @Override
        void send() {
            System.out.println("subject B send");
            super.mediator.relay(this);
        }
    }

    public static void main(String[] args) {
        Mediator mediator = new RealMediator();
        Subject subjectA = new SubjectA();
        Subject subjectB = new SubjectB();
        mediator.register(subjectA);
        mediator.register(subjectB);
        subjectA.send();
        subjectB.send();
    }
}
